﻿

using log4net;
using RemoteData.common;
using RemoteData.core.Listener;
using RemoteData.model.setting;
using System;
using System.IO;
using System.Net.Sockets;
using System.Windows;

namespace RemoteData.core
{
    public enum AppStatus
    {
        STARTED,
        QUIT
    }
    public class TW_App
    {
        private static ILog logger = LogManager.GetLogger(typeof(TW_App));

        public static string TITLE = "自定义协议数据";
        //public static string VERSION = "1.0.0";
        //public static string VERSION = "1.0.1";  // 协议头添加0x0820
        //public static string VERSION = "1.0.2";  // 转发器版本显示十六进制字符
        public static string VERSION = "1.0.3";  // 添加波峰强度和波长显示

        public static AppStatus appStatus = AppStatus.STARTED;

        public static ListenerManager listenerManager;

        /// <summary>
        /// 全局配置文件
        /// </summary>
        public static GlobalSetting globalSetting;
        /// <summary>
        /// 文件管理类
        /// </summary>
        public static FileManager fileManager;

        public TW_App() { }


        public static int Init()
        {
            fileManager = new FileManager();

            var fi = new FileInfo(fileManager.logConfigFile);
            log4net.Config.XmlConfigurator.Configure(fi);

            globalSetting = new GlobalSetting();
            int rn2 = globalSetting.Load();
            if (rn2 == -1)
            {
                string errmsg = string.Format("全局配置加载失败");
                logger.ErrorFormat(errmsg);
                return -3;
            }

            CreateListener(globalSetting.listenerPort);
            StartListener();

            return 0;
        }

        private static void CreateListener(int port)
        {
            try
            {
                UdpClient client = new UdpClient(port);
                client.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("监听端口被占用", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            listenerManager = new ListenerManager(port);
        }

        public static void StartListener()
        {
            listenerManager.StartAsync();
        }

        public static void StopListener()
        {
            listenerManager.Stop();
        }

        public static void ProgramQuit()
        {
            StopListener();
        }
    }
}
